
let db = require('../utils/DB');//数据库
let to = require('../utils/await-to-js');
let { SUCCESS1, ERROR, SUCCESS } = require('../utils/result');//结果
let jwt = require('../utils/jwt');
const updateModel = require('./updateModel');

/*
    查询购物车中是否包含该商品
    若购物车中没有这个商品，则  添加购物车
    若购物车中有这个商品，，更新功能
*/
//添加购物车商品
function addModel() {
    return async (req, res) => {

        let { token, goods_id, style_obj, goods_num } = req.query;//购物车商品id
        let { uid } = jwt.base64ToJson(token.split('.')[1]);//用户id

        let [err, rst] = await to(selectGoods(uid, goods_id));
        if (err) {    //查询失败
            ERROR(res, '新增购物车失败--查询', null);
            return;
        }

        if (rst.length > 0) {   //该数据已有，更新购物车
            let [err, data] = await to(updateShopcar(goods_num, goods_id, uid));
            err ? ERROR(res, '购车新增-更新失败', null) : SUCCESS1(res, '购物车新增-更新成功');
        } else {    //不包含该数据，添加购物车
            let [err, data] = await to(addShopcar(uid, goods_id, style_obj, goods_num));
            err ? ERROR(res, '新增购物车失败',err) : SUCCESS1(res, '添加购物成功');
        }
    };
}

//查询购物车中是否包含该商品
function selectGoods(uid, goodsId) {
    return db.query(`SELECT * FROM shopcar WHERE uid=? AND goods_id=?`, [uid, goodsId]);
}

//更新购物车
function updateShopcar(num, id, uid) {
    return db.query(`UPDATE  shopcar SET goods_num=? WHERE  goods_id=? AND uid=?`, [num, id, uid]);
}

//新增购物车数据
function addShopcar(uid, goodId, styleObj, num) {
    return db.query(`INSERT INTO shopcar (uid,goods_id,style_obj,goods_num) VALUES (?,?,?,?)`, [uid, goodId, styleObj, num]);
}


module.exports = addModel;